package com.codermn.并发访问控制.计数器CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * <p>
 *     计数，应用场景更偏向于多线程的协同，比如多个线程执行完毕之后，再处理某些事情；
 *     不同于上面的并发数的控制，它和栅栏一样，更多的是行为结果的统一
 *     重点：countDownLatch 计数为0时放行
 * </p>
 * @author jxau_scf
 * @date 2021/8/13 - 11:21
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(()->{
            try {
                System.out.println("do something in " + Thread.currentThread());
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }).start();

        new Thread(()->{
            try {
                System.out.println("do something in t2 " + Thread.currentThread());
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }).start();

        //阻塞主线程
        countDownLatch.await();
        System.out.println("结束");
    }
}
